package com.fa4j.system.settings.service.impl;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.common.base.util.ValidUtil;
import com.fa4j.system.settings.convert.SettingsConverter;
import com.fa4j.system.settings.model.Settings;
import com.fa4j.system.settings.model.SettingsCreateCmd;
import com.fa4j.system.settings.model.SettingsModifyCmd;
import com.fa4j.system.settings.repository.SettingsRepository;
import com.fa4j.system.settings.service.SettingsService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

/**
 * 系统设置 服务接口实现
 *
 * @since 2025-06-20 15:55:41
 */
@Slf4j
@Service
@Validated
@RequiredArgsConstructor
public class SettingsServiceImpl implements SettingsService {

    private final SettingsRepository settingsRepository;
    private final SettingsConverter settingsConverter;

    /**
     * 新增系统设置
     *
     * @param cmd 新增参数
     * @return 系统设置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Settings create(@Valid SettingsCreateCmd cmd) {
        ValidUtil.validInUsed("编码", cmd.getCode(), settingsRepository::findByCode);
        Settings entity = settingsConverter.toEntity(cmd);
        settingsRepository.create(entity);
        return entity;
    }

    /**
     * 编辑系统设置
     *
     * @param cmd 编辑参数
     * @return 系统设置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Settings modify(@Valid SettingsModifyCmd cmd) {
        Settings entity = settingsRepository.findById(cmd.getId())
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("系统设置"));
        settingsConverter.updateEntity(entity, cmd);
        settingsRepository.modify(entity);
        return entity;
    }

    /**
     * 删除系统设置
     *
     * @param cmd 删除参数
     * @return 系统设置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Settings remove(@Valid RemoveCmd<Integer> cmd) {
        Settings entity = settingsRepository.findById(cmd.getId())
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("系统设置"));
        entity.setOperatorId(cmd.getOperatorId());
        settingsRepository.remove(entity);
        return entity;
    }

}




